package main

import (
	"bytes"
	"fmt"
	"github.com/beevik/etree"
	"os"
	"strconv"
	"strings"
)

func main() {
	var fileName string
	fmt.Println("请输入kml文件名(包含后缀)")
	fmt.Scan(&fileName)
	doc := etree.NewDocument()
	if err := doc.ReadFromFile(fileName); err != nil {
		panic(err)
	}

	root := doc.SelectElement("kml")

	i := 1
	li := 1
	var buffer bytes.Buffer
	var lineBuffer bytes.Buffer
	for _, e := range root.FindElements("./Document//Placemark") {

		//节点名称（name）
		var name string
		for _, p := range e.FindElements("./name") {
			name = p.Text()
			fmt.Println(p.Text())
		}

		var description string
		for _, p := range e.FindElements("./description") {
			description = p.Text()
			fmt.Println(p.Text())
		}



		//标志桩点 （Point）
		for _, p := range e.FindElements("./Point[0]/coordinates[0]") {
			lonlat := p.Text()
			ts := strings.Split(lonlat, ",")
			lon := ts[0]
			lat := ts[1]

			//序号
			buffer.WriteString(strconv.Itoa(i))
			buffer.WriteString("\t")
			//标志物类型
			if(strings.Contains(name,"阀室")){
				buffer.WriteString("阀室")
				buffer.WriteString("\t")
			}else{
				buffer.WriteString("标示桩")
				buffer.WriteString("\t")
			}
			//标志物名称
			buffer.WriteString(name)
			buffer.WriteString("\t")
			//备注
			buffer.WriteString(description)
			buffer.WriteString("\t")
			//经度
			buffer.WriteString(lon)
			buffer.WriteString("\t")
			//纬度
			buffer.WriteString(lat)
			buffer.WriteString("\t")
			//fmt.Println(p.Text())
			buffer.WriteString("\n")
			i++
		}

		//管段 （Line）
		for _, p := range e.FindElements("./LineString[0]/coordinates[0]") {
			//经纬度
			lonlat := p.Text()
			lines := strings.Split(lonlat, " ")
			for _, l := range lines {
				ts := strings.Split(l, ",")

				if(len(ts)<2){
					continue
				}
				lon := ts[0]
				lat := ts[1]

				//序号
				lineBuffer.WriteString(strconv.Itoa(li))
				lineBuffer.WriteString("\t")

				//拐点顺序号
				lineBuffer.WriteString(strconv.Itoa(li))
				lineBuffer.WriteString("\t")

				//经度
				lineBuffer.WriteString(lon)
				lineBuffer.WriteString("\t")
				//纬度
				lineBuffer.WriteString(lat)
				lineBuffer.WriteString("\t")

				lineBuffer.WriteString("\n")
				li++
			}

			lineBuffer.WriteString("\n")
			li=1
		}

	}
	//fmt.Printf("%s", buffer.String())
	//fmt.Printf("%s", lineBuffer.String())
	fmt.Println("生成line.txt和point.txt中...")
	write("point.txt", buffer.String())
	write("line.txt", lineBuffer.String())
	fmt.Println("成功！")
	fmt.Println("已生成line.txt和point.txt。")
}

func write(path string, s string) {
	f, err := os.Create(path)
	if err != nil {
		fmt.Println(err)
		return
	}
	f.WriteString(s)
	f.Close()

}
